package com.hibernate.hrm.controller.position;

import com.hibernate.hrm.dao.DepartmentRepository;
import com.hibernate.hrm.dao.RoleRepository;
import com.hibernate.hrm.entity.Department;
import com.hibernate.hrm.entity.Position;
import com.hibernate.hrm.entity.User;
import com.hibernate.hrm.entity.dto.position.PositionAddDTO;
import com.hibernate.hrm.entity.dto.position.PositionEditDTO;
import com.hibernate.hrm.entity.dto.position.PositionListDTO;
import com.hibernate.hrm.entity.dto.position.PositionQueryDTO;
import com.hibernate.hrm.service.position.PositionService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/position")
@RequiredArgsConstructor
public class PositionController {

    private final PositionService positionService;
    private final DepartmentRepository departmentRepository;
    private final RoleRepository roleRepository;

    @GetMapping
    public String positionListPage(
            @RequestParam(value = "departmentId", required = false) Integer departmentId,
            @RequestParam(value = "positionName", required = false) String positionName,
            @RequestParam(value = "positionCode", required = false) String positionCode,
            @RequestParam(value = "page", defaultValue = "0") int page,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @AuthenticationPrincipal User currentUser,
            Model model) {

        // 构建查询DTO
        PositionQueryDTO queryDTO = new PositionQueryDTO();
        queryDTO.setDepartmentId(departmentId);
        queryDTO.setPositionName(positionName);
        queryDTO.setPositionCode(positionCode);
        queryDTO.setPageable(PageRequest.of(page, size, Sort.by("positionId").ascending()));

        // 获取职位列表
        Page<PositionListDTO> positions = positionService.getPositionList(queryDTO, currentUser);

        // 获取可访问的部门列表
        List<Department> departments = positionService.getAccessibleDepartments(currentUser);

        // 添加模型属性
        model.addAttribute("positions", positions);
        model.addAttribute("departments", departments);
        model.addAttribute("currentDepartmentId", departmentId);
        model.addAttribute("currentPositionName", positionName);
        model.addAttribute("currentPositionCode", positionCode);
        model.addAttribute("currentUser", currentUser);
        model.addAttribute("roleIdValue", currentUser.getRoleId().getRoleId());

        return "position";
    }

    @PostMapping("/toggle-status/{id}")
    public String togglePositionStatus(
            @PathVariable("id") Integer positionId,
            @AuthenticationPrincipal User currentUser,
            RedirectAttributes redirectAttributes) {

        try {
            positionService.togglePositionStatus(positionId, currentUser);
            redirectAttributes.addFlashAttribute("successMessage",
                    positionService.getPositionById(positionId, currentUser).getStatus() ?
                            "职位已成功启用" : "职位已成功禁用");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }
        return "redirect:/position";
    }

    @GetMapping("/view/{id}")
    public String viewPositionDetails(
            @PathVariable("id") Integer positionId,
            @AuthenticationPrincipal User currentUser,
            Model model) {

        Position position = positionService.getPositionById(positionId, currentUser);
        model.addAttribute("position", position);
        model.addAttribute("currentUser", currentUser);
        model.addAttribute("roleIdValue", currentUser.getRoleId().getRoleId());

        return "position-view";
    }

    @GetMapping("/edit/{id}")
    public String editPositionPage(
            @PathVariable("id") Integer positionId,
            @AuthenticationPrincipal User currentUser,
            Model model) {

        Position position = positionService.getPositionForEdit(positionId);
        model.addAttribute("position", position);
        model.addAttribute("departments", positionService.getAllActiveDepartments());
        model.addAttribute("roles", positionService.getAllRoles());
        model.addAttribute("currentUser", currentUser);
        model.addAttribute("roleIdValue", currentUser.getRoleId().getRoleId());

        return "position-edit";
    }

    @PostMapping("/edit/{id}")
    public String updatePosition(
            @PathVariable("id") Integer positionId,
            @ModelAttribute PositionEditDTO editDTO,
            @AuthenticationPrincipal User currentUser) {

        positionService.updatePosition(positionId, editDTO, currentUser);
        return "redirect:/position";
    }

    //新增职位
    @GetMapping("/add")
    public String showAddPositionPage(@AuthenticationPrincipal User currentUser, Model model) {
        // 确保currentUser不为null
        if (currentUser == null) {
            return "redirect:/login";
        }

        model.addAttribute("departments", departmentRepository.findByStatusTrue());
        model.addAttribute("roles", roleRepository.findAll());
        model.addAttribute("positionAddDTO", new PositionAddDTO());
        model.addAttribute("currentUser", currentUser);
        return "position-add";
    }

    @PostMapping("/add")
    public String addPosition(
            @ModelAttribute @Valid PositionAddDTO positionAddDTO,
            BindingResult bindingResult,
            @AuthenticationPrincipal User currentUser,
            RedirectAttributes redirectAttributes,
            Model model) {

        // 重新加载必要数据
        model.addAttribute("departments", departmentRepository.findByStatusTrue());
        model.addAttribute("roles", roleRepository.findAll());

        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                redirectAttributes.addFlashAttribute(error.getField() + "Error", error.getDefaultMessage());
            });
            return "redirect:/position/add";
        }

        try {
            positionService.addPosition(positionAddDTO, currentUser);
            redirectAttributes.addFlashAttribute("successMessage", "职位添加成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }

        return "redirect:/position";
    }

    @PostMapping("/delete/{id}")
    public String deletePosition(
            @PathVariable("id") Integer positionId,
            @AuthenticationPrincipal User currentUser,
            RedirectAttributes redirectAttributes) {

        try {
            positionService.deletePosition(positionId, currentUser);
            redirectAttributes.addFlashAttribute("successMessage", "职位删除成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", e.getMessage());
        }

        return "redirect:/position";
    }
}